import { Button, DatePicker, Form, Input, message, Select, Table, Tabs, notification } from 'antd';
const { TabPane } = Tabs;
import Progress from 'antd/es/progress';
import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';
import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { JSONObject } from 'seats/schema/common';
import { CallTaskCountMsg } from 'seats/schema/SocketMessage';
import { TaskInfo, TaskStatus } from 'seats/schema/Task';
import { getSeatSoundTempList, getTaskList, modifySeatFree } from 'seats/servers/servers';
import { getSocket } from 'servers/socket';
import { clearNull, getTableIndex } from 'utils/tools';
import ChooseSoundPop from './components/ChooseSoundPop';
import { getStatusName } from './TaskTool';
import { useSelector, useDispatch } from 'react-redux';
import qs from 'query-string';
import './style.scss';
import { setWorkspaceInfo, setCheckInState } from 'store/root/action';

const { RangePicker } = DatePicker;

/**我的任务 */
const CallTask: React.FC = () => {
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);
  const history = useHistory();
  /**存储当前页面table数据，方便socket中处理 */
  const tableDataRef = useRef<TaskInfo[]>([]);
  /**存储查询条件 */
  const searchRef = useRef<any>({
    taskName: '',
    taskStatus: 0,
    beginTime: '',
    endTime: '',
  });
  /**选择录音模板-弹窗 */
  const chooseSoundRef = useRef();
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // 查询条件
  const [taskName, setTaskName] = useState<string>('');
  const [beginTime, setBeginTime] = useState('');
  const [endTime, setEndTime] = useState('');
  const [taskStatus, setTaskStatus] = useState(TaskStatus.ALL);
  /**table列表数据 */
  const [tableData, setTableData] = useState<TaskInfo[]>([]);

  // 人人taskType 增加 taskType 任务类型 2：人机协同，3：人工自动外呼
  const [taskType, setTaskType] = useState((query.type || '2') as string);

  //  签入状态
  const checkInState = useSelector((state: JSONObject) => state.checkInState);
  const dispatch = useDispatch();
  /**
   * Table列描述数据对象 人机模式列
   */
  const columns_type_1: ColumnsType<TaskInfo> = [
    {
      title: '序号',
      fixed: 'left',
      dataIndex: 'index',
      render: (text: any, record: TaskInfo, index: number) =>
        getTableIndex(index, pageSize, current),
      width: 80,
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '机器人',
      dataIndex: 'robotName',
      key: 'robotName',
      width: 200,
    },
    {
      title: '外呼语音',
      dataIndex: 'soundType',
      key: 'soundType',
      render: (text: any, record: TaskInfo, index: number) => {
        return text === 1 ? '录音' : 'TTS';
      },
      width: 120,
    },
    {
      title: '任务状态',
      dataIndex: 'taskStatus',
      key: 'taskStatus',
      render: (text: any, record: TaskInfo, index: number) => {
        return getStatusName(record.taskStatus);
      },
      width: 100,
    },
    {
      title: '任务进度',
      dataIndex: 'finishedTaskNum',
      key: 'finishedTaskNum',
      width: 200,
      render: (text: any, record: TaskInfo, index: number) => {
        const process = Math.floor(
          (record.totalTaskNum ? record.finishedTaskNum / record.totalTaskNum : 0) * 100
        );
        /**进度条后-百分比格式 */
        const format = (percent?: number, successPercent?: number) => {
          return `${record.finishedTaskNum}/${record.totalTaskNum}`;
        };
        /**绿色进度条 */
        const successProcess = <Progress status="success" percent={process} size="small" />;
        /**红色进度条 */
        const errProcess = <Progress status="exception" percent={process} size="small" />;
        /**蓝色进度条 */
        const normalProcess = (
          <Progress status="active" percent={process} format={format} size="small" />
        );
        const statusMap = {
          0: normalProcess,
          1: normalProcess,
          2: normalProcess,
          3: successProcess,
          4: normalProcess,
          5: errProcess,
          6: errProcess,
          7: errProcess,
        };
        return <div className="process-task-seat">{statusMap[record.taskStatus]}</div>;
      },
    },
    {
      title: '创建人',
      dataIndex: 'nickName',
      key: 'nickName',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
    },
    {
      title: '执行时间段',
      dataIndex: 'allowTimes',
      key: 'allowTimes',
      width: 300,
      render: (text: any, record: TaskInfo) => {
        const itemStyle = { display: 'inline-block', paddingRight: 5 };
        const json = JSON.parse(text);
        const html = json.map((item: any, idx: number) => {
          return (
            <span key={idx} style={itemStyle}>
              {item.start}-{item.end}
            </span>
          );
        });
        return html;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      width: 100,
      render: (text: any, record: TaskInfo, index: number) => {
        return (
          <>
            <Button
              type="link"
              disabled={record.taskStatus !== 2}
              onClick={() => freeToWork(record)}
            >
              示闲
            </Button>
          </>
        );
      },
    },
  ];
  //人人模式 列
  const columns_type_2: ColumnsType<TaskInfo> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      fixed: 'left',
      render: (text: any, record: TaskInfo, index: number) =>
        getTableIndex(index, pageSize, current),
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '坐席组',
      dataIndex: 'seatsGroupName',
      key: 'seatsGroupName',
      width: 150,
    },
    {
      title: '任务进度',
      dataIndex: 'finishedTaskNum',
      key: 'finishedTaskNum',
      width: 200,
      render: (text: any, record: TaskInfo, index: number) => {
        const process = Math.floor(
          (record.totalTaskNum ? record.finishedTaskNum / record.totalTaskNum : 0) * 100
        );
        /**进度条后-百分比格式 */
        const format = (percent?: number, successPercent?: number) => {
          return `${record.finishedTaskNum}/${record.totalTaskNum}`;
        };
        /**绿色进度条 */
        const successProcess = <Progress status="success" percent={process} size="small" />;
        /**红色进度条 */
        const errProcess = <Progress status="exception" percent={process} size="small" />;
        /**蓝色进度条 */
        const normalProcess = (
          <Progress status="active" percent={process} format={format} size="small" />
        );
        const statusMap = {
          0: normalProcess,
          1: normalProcess,
          2: normalProcess,
          3: successProcess,
          4: normalProcess,
          5: errProcess,
          6: errProcess,
          7: errProcess,
        };
        return <div className="process-task-seat">{statusMap[record.taskStatus]}</div>;
      },
    },
    {
      title: '创建人',
      dataIndex: 'nickName',
      key: 'nickName',
      width: 150,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
    },
    {
      title: '执行时间段',
      dataIndex: 'allowTimes',
      key: 'allowTimes',
      width: 300,
      render: (text: any, record: TaskInfo) => {
        const itemStyle = { display: 'inline-block', paddingRight: 5 };
        const json = JSON.parse(text);
        const html = json.map((item: any, idx: number) => {
          return (
            <span key={idx} style={itemStyle}>
              {item.start}-{item.end}
            </span>
          );
        });
        return html;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      width: 100,
      render: (text: any, record: TaskInfo, index: number) => {
        return (
          <>
            <Button
              type="link"
              disabled={record.taskStatus !== 2}
              onClick={() => freeToWork(record)}
            >
              示闲
            </Button>
          </>
        );
      },
    },
  ];

  /**时间选择器-格式定义 */
  const dateFormat = 'YYYY-MM-DD';

  /**
   * 列表数据-初始化
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getTaskList(
        clearNull({
          pageNo: current,
          pageSize: pageSize,
          taskName: searchRef.current.taskName,
          taskStatus: searchRef.current.taskStatus > 0 ? searchRef.current.taskStatus : '',
          beginTime: searchRef.current.beginTime,
          endTime: searchRef.current.endTime,
          taskType: taskType,
        })
      );
      const { data, count } = res;
      setTableData(data || []);
      tableDataRef.current = data;
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, taskType]);
  /**
   * 绑定socket事件
   */
  const addSocketEvent = () => {
    getSocket().addEvent('callTaskStatusBroadcastEvent', (data: JSONObject) => {
      setTimeout(() => {
        // console.log(data, '我的任务callTaskStatusBroadcastEvent');
        data = data as CallTaskCountMsg;
        if (!tableDataRef.current) return;
        // 原来的table数据
        const copyTableData = JSON.parse(JSON.stringify(tableDataRef.current));
        copyTableData.forEach((item: any) => {
          if (item.taskId.toString() === data.taskId) {
            item.taskStatus = data.taskStatus || item.taskStatus;
            item.totalTaskNum = data.countTotal || item.totalTaskNum;
            item.finishedTaskNum = data.countComplete || item.finishedTaskNum;
          }
        });
        tableDataRef.current = JSON.parse(JSON.stringify(copyTableData));
        // 重置列表数据，包含已完成，刷新后-更新
        setTableData(tableDataRef.current);
      }, 0);
    });
  };

  const removeSocketEvent = () => {
    getSocket().removeEvent(['callTaskStatusBroadcastEvent']);
  };
  // 1-初始化数据
  useEffect(() => {
    initData();
  }, [initData]);
  // 2-socket相关
  useEffect(() => {
    addSocketEvent();
    return () => {
      removeSocketEvent();
    };
  }, []);

  /**时间范围选择 */
  function onDateChange(value: any, dateString: any) {
    setBeginTime(dateString[0]);
    setEndTime(dateString[1]);
  }
  /**
   * 重置列表
   */
  const resetTable = () => {
    if (current !== 1) {
      setCurrent(1);
      return;
    }
    initData();
  };
  /**
   * 操作-搜索
   */
  const handleSearch = () => {
    searchRef.current = {
      taskName,
      taskStatus,
      beginTime,
      endTime,
    };
    resetTable();
  };

  /**
   * 操作-重置
   */
  function resetSearch() {
    // 重置搜索条件；重置列表
    setTaskName('');
    setTaskStatus(0);
    setBeginTime('');
    setEndTime('');
    searchRef.current = {
      taskName: '',
      taskStatus: '',
      beginTime: '',
      endTime: '',
    };
    resetTable();
  }

  /**操作：示闲 */
  async function freeToWork(record: TaskInfo) {
    setTableLoading(true);
    if (checkInState !== 2) {
      // 没有签入成功，则提示请签入
      message.warn('抱歉，请先签入');
      setTableLoading(false);
      return;
    }

    // 人人任务类型
    if (record.flowType === 3) {
      await doSeatFreeForPP(record);
    } else {
      if (record.soundType > 0) {
        // 1.外呼语音：录音
        // 检测是否存在录音模板
        try {
          const res = await getSeatSoundTempList(
            clearNull({
              pageNo: 1,
              pageSize: 10000,
              templateStatus: 1,
              robotId: record.robotId,
              type: 1,
            })
          );
          const { count } = res;
          if (count) {
            // 1-1.有录音模板，选择录音模板弹窗
            (chooseSoundRef.current as any).open(record, (soundTemplateId: number) => {
              // 回调函数
              // 跳转示闲页面，操作-示闲任务
              doSeatFree(record, soundTemplateId);
            });
          } else {
            // 1-2.没有录音模板，toast提示录音
            message.info('请先对机器人进行录音');
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      } else {
        // 2.外呼语音：TTS
        // 操作-示闲任务
        console.log('TTS 直接跳至 workspace');
        // 操作-示闲任务
        doSeatFree(record);
      }
    }

    setTableLoading(false);
  }

  /**
   * 请求示闲接口 人机任务
   * 接口使用场景：任务列表点击示闲
   * @param {number} taskInfo 任务基本信息
   */
  async function doSeatFree(taskInfo: TaskInfo, soundTemplateId?: number) {
    const { taskId, soundType } = taskInfo;
    try {
      await modifySeatFree(
        taskId,
        clearNull({
          templateId: soundType ? soundTemplateId : undefined,
          seatsSession: 1,
        })
      );

      dispatch(setWorkspaceInfo(taskInfo));

      console.log('✅ 任务列表页面-操作-示闲成功');
      history.push('/webseats/seats/callTask/workspace');
    } catch (error) {
      console.log('任务列表页面-示闲失败');
      dispatch(setCheckInState(1));
      notification.error({
        message: '示闲任务失败！',
        description: '请重新进行签入操作',
      });
    }
  }

  /**
   * 请求示闲接口 人人任务
   * 接口使用场景：1.任务列表点击示闲
   * @param {number} taskInfo 任务基本信息
   */
  async function doSeatFreeForPP(taskInfo: TaskInfo) {
    const { taskId } = taskInfo;
    try {
      await modifySeatFree(taskId, {});

      dispatch(setWorkspaceInfo(taskInfo));

      console.log('✅ 任务列表页面-操作-示闲成功');
      history.push('/webseats/seats/callTask/WorkspaceForPP');
    } catch (error) {
      console.log('任务列表页面-示闲失败');
      dispatch(setCheckInState(1));
      notification.error({
        message: '示闲任务失败！',
        description: '请重新进行签入操作',
      });
    }
  }

  // tab切换
  const callback = (key: string) => {
    setTaskType(key);
    history.replace('/webseats/seats/callTask?type=' + key);
  };
  return (
    <>
      <Tabs className="callTask" activeKey={taskType} onChange={callback}>
        <TabPane tab="人机协同任务" key="2" />
        <TabPane tab="人工自动外呼任务" key="3" />
      </Tabs>
      <div className="mgr-header seat-task-list-header">
        <div className="mgr-header-left">
          <Form layout="inline">
            <Form.Item label="任务名称">
              <Input
                placeholder="请输入任务名称"
                value={taskName}
                onChange={e => {
                  console.log('输入的查询条件', e.target.value.trim());
                  setTaskName(e.target.value.trim());
                }}
              />
            </Form.Item>
            <Form.Item label="任务状态">
              <Select
                value={taskStatus}
                options={taskStatusOption}
                onChange={val => {
                  setTaskStatus(val);
                }}
              />
            </Form.Item>
            <Form.Item label="创建日期">
              <RangePicker
                value={
                  beginTime && endTime
                    ? [moment(beginTime, dateFormat), moment(endTime, dateFormat)]
                    : null
                }
                ranges={{
                  今天: [moment().startOf('day'), moment().endOf('day')],
                  本周: [moment().startOf('week'), moment().endOf('week')],
                  本月: [moment().startOf('month'), moment().endOf('month')],
                }}
                onChange={onDateChange}
                allowClear
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" ghost onClick={resetSearch}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      <div className="mgr-table">
        <Table
          loading={tableLoading}
          columns={taskType === '3' ? columns_type_2 : columns_type_1}
          scroll={{ x: '100%' }}
          dataSource={tableData}
          rowKey="taskId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>

      <ChooseSoundPop cRef={chooseSoundRef} />
    </>
  );
};

const taskStatusOption = [
  {
    value: 0,
    label: '全部',
  },
  {
    value: 2,
    label: '进行中',
  },
  {
    value: 5,
    label: '禁呼中',
  },
  {
    value: 7,
    label: '已暂停',
  },
];

export default CallTask;
